package com.qiangesoft.rdp.starter.captcha.config;

import com.qiangesoft.rdp.starter.captcha.core.CaptchaLocalStoreImpl;
import com.qiangesoft.rdp.starter.captcha.core.CaptchaStore;
import com.qiangesoft.rdp.starter.captcha.core.EasyCaptchaTemplate;
import com.qiangesoft.rdp.starter.captcha.core.EasyCaptchaTemplateImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * captcha自动配置
 *
 * @author qiangesoft
 * @date 2023-09-15
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(CaptchaProperties.class)
public class CaptchaConfiguration implements ApplicationContextAware {

    private final CaptchaProperties captchaProperties;

    public CaptchaConfiguration(CaptchaProperties captchaProperties) {
        this.captchaProperties = captchaProperties;
    }

    private ApplicationContext applicationContext;

    @Bean
    @ConditionalOnMissingBean
    public EasyCaptchaTemplate captchaService() {
        return new EasyCaptchaTemplateImpl(captchaProperties, captchaStore());
    }

    @Bean
    @ConditionalOnMissingBean
    public CaptchaStore captchaStore() {
        CaptchaStore captchaStore;
        Class<? extends CaptchaStore> storeImpl = captchaProperties.getStoreImpl();
        if (storeImpl == null || storeImpl.equals(CaptchaLocalStoreImpl.class)) {
            captchaStore = new CaptchaLocalStoreImpl(captchaProperties);
        } else {
            captchaStore = applicationContext.getBean(storeImpl);
        }
        return captchaStore;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
